/********************************************************************************
 * Project Name		[JavaEE_Components]
 * File Name     	[UserDao.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package javamail.cases.dao;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

import javamail.cases.bean.User;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class UserDao {

	private static UserDao userDao = new UserDao();

	public static UserDao getInstance() {
		return userDao;
	}

	Map<Integer, User> users = new LinkedHashMap<>();

	private UserDao() {
		super();
	}

	private int nextId = 1;

	/**
	 * 添加用户
	 * 
	 * @param user
	 */
	public void addUser(User user) {
		user.setId(++nextId);
		user.setRandomCode(UUID.randomUUID().toString());
		users.put(user.getId(), user);
	}

	/**
	 * 更新用户
	 * 
	 * @param user
	 */
	public void updateUser(User user) {
		users.put(user.getId(), user);
	}

	/**
	 * 根据ID查找用户
	 * 
	 * @param id
	 * @return
	 */
	public User findUserById(Integer id) {
		return users.get(id);
	}

	/**
	 * 根据名字查找用户
	 * 
	 * @param username
	 * @return
	 */
	public User findUserByName(String username) {
		Collection<User> userValues = users.values();
		for (User user : userValues) {
			if (user.getUsername().equals(username)) {
				return user;
			}
		}
		return null;
	}

	/**
	 * 根据用户名或Email查找用户
	 * 
	 * @param criteria
	 * @return
	 */
	public User findUserByNameOrEmail(String criteria) {
		Collection<User> userValues = users.values();
		for (User user : userValues) {
			if (user.getUsername().equals(criteria) || user.getEmail().equals(criteria)) {
				return user;
			}
		}
		return null;
	}
}
